package com.party.course.service.impl;

import java.math.BigDecimal;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.date.DateUtil;
import com.party.common.core.domain.AjaxResult;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.utils.StringUtils;
import com.party.course.domain.*;
import com.party.course.mapper.AmountInfoMapper;
import com.party.course.mapper.StudentInfoMapper;
import com.party.course.service.IPayReqInfoService;
import com.party.course.service.IRealNameInfoService;
import com.party.course.util.XunpayUtil;
import com.party.pay.XunayRefundResponse;
import com.party.pay.XunayRefundService;
import com.party.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.party.course.mapper.ApprovalInfoMapper;
import com.party.course.service.IApprovalInfoService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.party.common.utils.SecurityUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 审批申请Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class ApprovalInfoServiceImpl extends ServiceImpl<ApprovalInfoMapper, ApprovalInfo> implements IApprovalInfoService {
    @Resource
    private ApprovalInfoMapper approvalInfoMapper;
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Resource
    private AmountInfoMapper amountInfoMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private IPayReqInfoService payReqInfoService;

    /**
     * 查询审批申请
     *
     * @param id 审批申请主键
     * @return 审批申请
     */
    @Override
    public ApprovalInfo view(String id) {
        return approvalInfoMapper.selectApprovalInfoById(id);
    }

    /**
     * 查询审批申请列表
     *
     * @param approvalInfo 审批申请
     * @return 审批申请
     */
    @Override
    public List<ApprovalInfo> findList(ApprovalInfo approvalInfo) {
        return approvalInfoMapper.selectApprovalInfoList(approvalInfo);
    }

    /**
     * 新增审批申请
     *
     * @param approvalInfo 审批申请
     * @return 结果
     */
    @Override
    public int add(ApprovalInfo approvalInfo) {
        if (StringUtils.isNotEmpty(approvalInfo.getBusinessType()) && ("2".equals(approvalInfo.getBusinessType())||"1".equals(approvalInfo.getBusinessType()))) {
            //合伙人通账户申请
            approvalInfo.setApprover("1");
            approvalInfo.setApproverName("admin");
        }
        SysUser user = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        if (ObjectUtil.isNotEmpty(user)){
            approvalInfo.setAppUserId(SecurityUtils.getUserIdStr());
            approvalInfo.setAppUserName(user.getUserName());
        }
        approvalInfo.setId(IdUtil.simpleUUID());
        approvalInfo.setStatus("0");
        approvalInfo.setDelFlag("0");
        return approvalInfoMapper.insert(approvalInfo);
    }


    @Autowired
    private IRealNameInfoService realNameInfoService;


    @Autowired
    private XunayRefundService refundService;
    /**
     * 修改审批申请
     *
     * @param approvalInfo 审批申请
     * @return 结果
     */
    @Override
    @Transactional
    public int updateEntity(ApprovalInfo approvalInfo) {
        try {
            if ("0".equals(approvalInfo.getBusinessType())) {
                //退课退款申请
                StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(approvalInfo.getBusinessId());
                BigDecimal changeAmount = approvalInfo.getChangeAmount();
                String orderCode = studentInfo.getOrderCode();
                studentInfo.setApprovalRemark(approvalInfo.getRemark());
                if (ObjectUtil.isNotEmpty(studentInfo)) {
                    if ("1".equals(approvalInfo.getStatus())) {
                        studentInfo.setApprovalStatus("2");
                        studentInfo.setOrderStatus("1");
                        studentInfo.setSurplusLearnTime("0");
                        // 调用退款接口
                        Long aLong = XunpayUtil.convertYuanToCent(changeAmount.toString());
                        // aLong 转成 int
                        int amont = aLong.intValue();

                        XunayRefundResponse response = refundService.applyRefund(
                                orderCode, IdUtil.simpleUUID(),amont , "退款");

                    }else {
                        studentInfo.setApprovalStatus("3");

                    }
                    studentInfoMapper.updateById(studentInfo);
                }
            }else if ("1".equals(approvalInfo.getBusinessType())) {
                //提现申请
                AmountInfo amountInfo = amountInfoMapper.selectAmountInfoById(approvalInfo.getBusinessId());
                if (ObjectUtil.isNotEmpty(amountInfo)) {
                    if ("1".equals(approvalInfo.getStatus())) {
                        //三方支付提现 并 通过回调 修改状态和用户余额
                        BigDecimal changeAmount = amountInfo.getChangeAmount();
                        String userId = amountInfo.getUserId();
                        RealNameInfo realNameInfo = realNameInfoService.findByUserId(userId);
                        if(realNameInfo==null){
                            throw new RuntimeException("请先签约，提现失败");
                        }
                        String applicationStatus = realNameInfo.getApplicationStatus();
                        if(!"COMPLETED".equals(applicationStatus)){
                            throw new RuntimeException("请先签约完成，提现失败");
                        }
                        String merchantNo = realNameInfo.getMerchantNo();
                        String bankCardNo = realNameInfo.getBankCardNo();
                        PayReqInfo reqInfo = XunpayUtil.transparent(amountInfo.getId()+IdUtil.simpleUUID(),changeAmount,merchantNo,bankCardNo);
                        System.out.println("========================reqInforeqInforeqInforeqInfo=======");
                        int add = payReqInfoService.add(reqInfo);
                        System.out.println("========================addaddaddaddaddadd======="+add);
                        if (add == 1) {
                            System.out.println("========================add == 1)add == 1)add == 1)add == 1)add == 1)======="+add);
                            approvalInfo.setUpdateTime(DateUtil.date());
                            approvalInfoMapper.updateById(approvalInfo);
                            amountInfoMapper.updateById(amountInfo);
                            return add;
                        }
                    }else {
                        amountInfo.setValidTime(null);
                        amountInfo.setCashStatus("2");
                        SysUser user = sysUserMapper.selectUserById(Long.valueOf(amountInfo.getUserId()));
                        System.out.println("=======user.getAmount()user.getAmount()user.getAmount()======"+user.getAmount());
                        System.out.println("=======user.getChangeAmount()user.getChangeAmount()user.getChangeAmount()======"+amountInfo.getChangeAmount());
                        if (user != null) {
                            user.setAmount(user.getAmount().add(amountInfo.getChangeAmount()));
                            sysUserMapper.updateUser(user);
                        }
                    }
                    amountInfoMapper.updateById(amountInfo);
                }
            }
            approvalInfo.setUpdateTime(DateUtil.date());
            return approvalInfoMapper.updateById(approvalInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 批量删除审批申请
     *
     * @param ids 需要删除的审批申请主键
     * @return 结果
     */
    @Override
    public int deleteIds(List<String> ids) {
        return approvalInfoMapper.deleteApprovalInfoByIds(ids);
    }

    /**
     * 删除审批申请信息
     *
     * @param id 审批申请主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return approvalInfoMapper.deleteApprovalInfoById(id);
    }
}
